<template>
  <div>
    <div class="form-section">
      <el-row :gutter="20">
        <!-- 表单提交 -->
        <el-col :xs="xs" :sm="sm" :md="md">
          <el-form-item-plus
            :label="$t('menu.dev.field.field.form_post', '表单录入')"
            prop="config.form_post"
          >
            <el-radio-group
              v-model="modelValue.config.form_post"
              :style="commonInputStyle"
            >
              <el-radio :value="1">是</el-radio>
              <el-radio :value="0">否</el-radio>
            </el-radio-group>
          </el-form-item-plus>
        </el-col>

        <!-- 必填项 -->
        <el-col :xs="xs" :sm="sm" :md="md" v-if="showFormConfig">
          <el-form-item-plus
            :label="$t('menu.dev.field.field.item_required', '是否必填')"
            prop="config.item_required"
          >
            <el-radio-group
              v-model="modelValue.config.item_required"
              :style="commonInputStyle"
            >
              <el-radio value="optional">可选</el-radio>
              <el-radio value="required">必填</el-radio>
            </el-radio-group>
          </el-form-item-plus>
        </el-col>

        <!-- 默认值 -->
        <el-col :xs="xs" :sm="sm" :md="md" v-if="!isApi && showFormConfig">
          <el-form-item-plus
            :label="$t('menu.dev.field.field.item_default', '表单默认值')"
            prop="config.item_default"
            tooltipContent="需要根据不同类型的字段自行设置，如设置错误，可能导致程序出错"
          >
            <el-input
              :placeholder="
                $p('menu.dev.field.field.item_default', '表单默认值')
              "
              v-model="modelValue.config.item_default"
              :style="commonInputStyle"
            />
          </el-form-item-plus>
        </el-col>

        <!-- 占位符 -->
        <el-col :xs="xs" :sm="sm" :md="md" v-if="!isApi && showFormConfig">
          <el-form-item-plus
            :label="$t('menu.dev.field.field.item_placeholder', '占位符')"
            prop="config.item_placeholder"
            tooltipContent="禁用多语言则直接编写提示信息，若开启多语言则填写多语言key"
          >
            <el-input
              :placeholder="
                $p('menu.dev.field.field.item_placeholder', '占位符')
              "
              v-model="modelValue.config.item_placeholder"
              :style="commonInputStyle"
            />
          </el-form-item-plus>
        </el-col>
        <!-- 提示信息 -->
        <el-col :xs="xs" :sm="sm" :md="md" v-if="!isApi && showFormConfig">
          <el-form-item-plus
            :label="$t('menu.dev.field.field.item_tooltip', '提示信息')"
            prop="config.item_tooltip"
            tooltipContent="禁用多语言则直接编写提示信息，若开启多语言则填写多语言key"
          >
            <el-input
              :placeholder="$p('menu.dev.field.field.item_tooltip', '提示信息')"
              v-model="modelValue.config.item_tooltip"
              :style="commonInputStyle"
            />
          </el-form-item-plus>
        </el-col>

        <!-- 显示条件 -->
        <el-col :xs="xs" :sm="sm" :md="md" v-if="!isApi && showFormConfig">
          <el-form-item-plus
            :label="$t('menu.dev.field.field.item_when', '显示条件')"
            prop="config.item_when"
          >
            <el-input
              :placeholder="$p('menu.dev.field.field.item_when', '显示条件')"
              v-model="modelValue.config.item_when"
              :style="commonInputStyle"
            />
          </el-form-item-plus>
        </el-col>
      </el-row>
      <el-row :gutter="20" v-if="showFormConfig">
        <!-- 单选还是多选 -->
        <el-col :xs="xs" :sm="sm" :md="md" v-if="showMultipleSelect">
          <el-form-item-plus
            :label="$t('menu.dev.field.field.item_multiple', '选择类型')"
            prop="config.item_multiple"
          >
            <el-radio-group
              v-model="modelValue.config.item_multiple"
              :style="commonInputStyle"
              @change="handleSelectTypeChange"
            >
              <el-radio value="single">单选</el-radio>
              <el-radio value="multiple">多选</el-radio>
            </el-radio-group>
          </el-form-item-plus>
        </el-col>
        <!-- 选项类型 -->
        <el-col :xs="xs" :sm="sm" :md="md" v-if="showSelectType">
          <el-form-item-plus
            :label="$t('menu.dev.field.field.item_option_type', '选项类型')"
            prop="config.item_required"
          >
            <el-radio-group
              v-model="modelValue.config.item_options_type"
              :style="commonInputStyle"
            >
              <el-radio value="dict">字典</el-radio>
              <el-radio value="sql" :disabled="disableSqlAndKeyValue"
                >SQL
              </el-radio>
              <el-radio
                value="key_value"
                :disabled="disableSqlAndKeyValue || disableKeyValue"
                >自定义
              </el-radio>
            </el-radio-group>
          </el-form-item-plus>
        </el-col>

        <!-- 字典选项-键值对 -->
        <el-col :span="24" v-if="showKvOptions">
          <el-form-item-plus
            :label="$t('menu.dev.field.field.item_options', '选项')"
            prop="config.item_options"
          >
            <ra-array-editor
              :isTree="false"
              v-model="modelValue.config.item_options"
              :style="commonInputStyle"
            />
          </el-form-item-plus>
        </el-col>

        <!-- 字典选项-SQL查询 -->
        <el-col :span="8" v-if="showSqlOptions">
          <el-form-item-plus
            label="数据权限"
            prop="config.is_permission"
            tooltipContent="是否根据用户的数据权限返回SQL查询的字典数据"
          >
            <el-radio-group
              v-model="modelValue.config.is_permission"
              :style="commonInputStyle"
              @change="handleSelectTypeChange"
            >
              <el-radio :value="1">启用</el-radio>
              <el-radio :value="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item-plus>
        </el-col>
        <el-col :span="8" v-if="showSqlOptions">
          <el-form-item-plus
            label="远程搜索"
            prop="config.remote_enabled"
            tooltipContent="是否启用远程搜索"
          >
            <el-radio-group
              v-model="modelValue.config.remote_enabled"
              :style="commonInputStyle"
              @change="handleSelectTypeChange"
            >
              <el-radio :value="1">启用</el-radio>
              <el-radio :value="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item-plus>
        </el-col>
        <el-col :span="8" v-if="showSqlOptions && showSelectRemoteSearch">
          <el-form-item-plus
            label="搜索字段"
            prop="config.remote_search_field"
            tooltipContent="要远程搜索的字段名是什么"
          >
            <el-input
              v-model="modelValue.config.remote_search_field"
              :style="commonInputStyle"
            />
          </el-form-item-plus>
        </el-col>
        <el-col :span="8" v-if="showSqlOptions && showSelectRemoteSearch">
          <el-form-item-plus
            label="分页大小"
            prop="config.remote_page_size"
            tooltipContent="远程搜索的分页大小"
          >
            <el-input-number
              v-model="modelValue.config.remote_page_size"
              :style="commonInputStyle"
            />
          </el-form-item-plus>
        </el-col>
        <el-col :span="24" v-if="showSqlOptions">
          <el-form-item-plus
            :label="$t('menu.dev.field.field.item_options', '选项')"
            prop="config.item_options"
            :tooltipContent="
              $t(
                'menu.dev.field.tip.sql',
                '输入的SQL语句必须包含label、value、pid(树)字段，如果级联选择则需明确字段占位符',
              )
            "
          >
            <el-input
              type="textarea"
              v-model="modelValue.config.item_options"
              :rows="4"
              :style="commonInputStyle"
            />
            <el-link
              type="primary"
              @click="fillCommonSQL"
              class="font-200 text-12px"
            >
              普通SQL查询模板
            </el-link>
            <el-link
              type="primary"
              @click="fillTreeSQL"
              class="font-200 text-12px ml-5"
            >
              树形SQL查询模板
            </el-link>
          </el-form-item-plus>
        </el-col>

        <!-- 字典选项-预定义字典 -->
        <el-col :xs="xs" :sm="sm" :md="md" v-if="showDictOptions">
          <el-form-item-plus
            :label="$t('menu.dev.field.field.item_options', '选项')"
            prop="config.item_options"
          >
            <div class="flex w-[100%]">
              <el-select
                v-model="modelValue.config.item_options"
                :placeholder="
                  $p('menu.dev.field.field.item_options', '选项', 'select')
                "
                style="width: 100%"
              >
                <el-option
                  v-for="item in selectOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <el-button
                type="primary"
                @click="handleShowDictDialog"
                class="ml-1"
              >
                创建字典
              </el-button>
            </div>
          </el-form-item-plus>
        </el-col>
      </el-row>
      <el-row :gutter="20" v-if="showFormConfig">
        <!-- 地图组件 -->
        <el-col :xs="xs" :sm="sm" :md="md" v-if="showLocationMap">
          <el-form-item-plus
            :label="$t('menu.dev.field.field.item_map', '地图组件')"
            prop="config.item_map"
          >
            <el-select
              v-model="modelValue.config.item_map"
              :style="commonInputStyle"
              :placeholder="
                $p('menu.dev.field.field.item_map', '地图组件', 'select')
              "
            >
              <el-option label="百度地图" value="baidumap" />
              <el-option label="腾讯地图" value="qqmap" />
              <el-option label="高德地图" value="amap" />
            </el-select>
          </el-form-item-plus>
        </el-col>

        <!-- 编辑器 -->
        <el-col :xs="xs" :sm="sm" :md="md" v-if="showRichTextEditor">
          <el-form-item-plus
            :label="$t('menu.dev.field.field.item_editor', '编辑器')"
            prop="config.item_editor"
          >
            <el-select
              v-model="modelValue.config.item_editor"
              :style="commonInputStyle"
              :placeholder="
                $p('menu.dev.field.field.item_editor', '编辑器', 'select')
              "
            >
              <el-option label="WangEditor" value="wangeditor" />
              <el-option label="Tinymce" value="tinymce" />
              <el-option label="MarkDown" value="markdown" />
            </el-select>
          </el-form-item-plus>
        </el-col>

        <!-- 省市区联动 -->
        <el-col :xs="xs" :sm="sm" :md="md" v-if="showSsq">
          <el-form-item-plus
            :label="$t('menu.dev.field.field.item_ssq', '省市区')"
            prop="config.item_editor"
          >
            <el-select
              v-model="modelValue.config.grid_render_function"
              :style="commonInputStyle"
              :placeholder="
                $p('menu.dev.field.field.item_ssq', '省市区', 'select')
              "
            >
              <el-option label="省市区三级联动" value="regionData" />
              <el-option label="省市二级联动" value="provinceAndCityData" />
            </el-select>
          </el-form-item-plus>
        </el-col>

        <!-- 图片上传 -->
        <el-col :xs="xs" :sm="sm" :md="md" v-if="showImageUpload">
          <el-form-item-plus
            :label="$t('menu.dev.field.field.item_image_upload', '图片上传')"
            prop="config.item_image_upload"
          >
            <el-select
              v-model="modelValue.config.item_image_upload"
              :style="commonInputStyle"
              :placeholder="
                $p(
                  'menu.dev.field.field.item_image_upload',
                  '图片上传',
                  'select',
                )
              "
              @change="handleSelectUploadChange"
            >
              <el-option
                label="输入框上传组件（单）"
                value="ra-upload-input-single"
              />
              <el-option
                label="缩略图上传组件（单）"
                value="ra-upload-card-single"
              />
              <el-option
                label="图片列表上传组件（单）"
                value="ra-upload-list-single"
              />
              <el-option
                label="缩略图上传组件（多）"
                value="ra-upload-card-multiple"
              />
              <el-option
                label="图片列表上传组件（多）"
                value="ra-upload-list-multiple"
              />
            </el-select>
          </el-form-item-plus>
        </el-col>

        <!-- 文件上传 -->
        <el-col :xs="xs" :sm="sm" :md="md" v-if="showFileUpload">
          <el-form-item-plus
            :label="$t('menu.dev.field.field.item_file_upload', '文件上传')"
            prop="config.item_file_upload"
          >
            <el-select
              v-model="modelValue.config.item_file_upload"
              :style="commonInputStyle"
              :placeholder="
                $p(
                  'menu.dev.field.field.item_file_upload',
                  '上传文件',
                  'select',
                )
              "
              @change="handleSelectUploadChange"
            >
              <el-option
                label="输入框上传组件（单）"
                value="ra-upload-input-single"
              />
              <el-option
                label="文件列表上传组件（单）"
                value="ra-upload-list-single"
              />
              <el-option
                label="文件列表上传组件（多）"
                value="ra-upload-list-multiple"
              />
            </el-select>
          </el-form-item-plus>
        </el-col>
        <el-col
          :xs="xs"
          :sm="sm"
          :md="md"
          v-if="
            (showFileUpload &&
              modelValue.config.item_file_upload ===
                'ra-upload-list-multiple') ||
            (showImageUpload &&
              (modelValue.config.item_image_upload ===
                'ra-upload-card-multiple' ||
                modelValue.config.item_image_upload ===
                  'ra-upload-list-multiple'))
          "
        >
          <el-form-item-plus
            :label="$t('menu.dev.field.field.item_max_count', '最大数量')"
            prop="config.item_max_count"
          >
            <el-input-number v-model="modelValue.config.item_max_count" />
          </el-form-item-plus>
        </el-col>

        <!-- 文本域行数 -->
        <el-col :xs="xs" :sm="sm" :md="md" v-if="showTextareaRows">
          <el-form-item-plus
            :label="$t('menu.dev.field.field.item_rows', '编辑区域高度')"
            prop="config.item_rows"
          >
            <el-input
              v-model="modelValue.config.item_rows"
              :style="commonInputStyle"
              :placeholder="
                $p('menu.dev.field.field.item_rows', '编辑区域高度')
              "
            />
          </el-form-item-plus>
        </el-col>

        <!-- 日期类型 -->
        <el-col :xs="xs" :sm="sm" :md="md" v-if="showDateType">
          <el-form-item-plus
            :label="$t('menu.dev.field.field.item_date_type', '日期类型')"
            prop="config.item_date_format"
            tooltipContent="请选择日期选择器的类型"
          >
            <el-select
              v-model="modelValue.config.item_date_type"
              :placeholder="
                $p('menu.dev.field.field.item_date_type', '日期类型', 'select')
              "
              :style="commonInputStyle"
            >
              <el-option
                v-for="option in dateTypeOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item-plus>
        </el-col>

        <!-- 日期格式 -->
        <el-col :xs="xs" :sm="sm" :md="md" v-if="showDateType">
          <el-form-item-plus
            :label="$t('menu.dev.field.field.item_date_format', '日期格式')"
            prop="config.item_date_format"
            tooltipContent="格式类似：YYYY-MM-DD HH:mm:ss"
          >
            <el-input
              v-model="modelValue.config.item_date_format"
              :style="commonInputStyle"
              :placeholder="
                $p('menu.dev.field.field.item_date_format', '日期格式')
              "
            />
          </el-form-item-plus>
        </el-col>
      </el-row>
      <el-row :gutter="20" v-if="showFormConfig">
        <!-- 列表选择器 -->
        <el-col :span="24" v-if="showListSelector">
          <el-form-item-plus
            :label="$t('menu.dev.field.field.item_menu_url')"
            prop="config.item_menu"
          >
            <ra-list-select-config
              v-model="modelValue.config.item_menu"
              :style="commonInputStyle"
            ></ra-list-select-config>
          </el-form-item-plus>
        </el-col>
      </el-row>
      <el-row :gutter="20" v-if="showFormConfig">
        <!-- 正则表达式验证 -->
        <el-col :span="16" v-if="showValidation">
          <el-form-item-plus
            :label="$t('menu.dev.field.field.item_validate', '表单验证')"
            prop="config.item_regular_content"
          >
            <div class="flex items-center w-full">
              <el-input
                class="w-[70%]"
                v-model="modelValue.config.item_regular_content"
                :style="commonInputStyle"
                :placeholder="
                  $p(
                    'menu.dev.field.field.item_regular_content',
                    '验证规则内容',
                  )
                "
              />
              <ra-dict-select
                class="ml-2 w-[30%]"
                :placeholder="
                  $p(
                    'menu.dev.field.field.item_regular_content',
                    '表单验证',
                    'select',
                  )
                "
                type="select"
                code="validate_options"
                :editable="true"
                ref="regularRef"
                v-model="modelValue.config.item_regular_content"
                :style="commonInputStyle"
                @change="handleSelectRegularChange"
              />
            </div>
          </el-form-item-plus>
        </el-col>
      </el-row>
    </div>
    <div v-if="!showFormConfig && (showRandomLength || showOrderSn)">
      <el-row :gutter="20">
        <!-- 随机数长度 -->
        <el-col :xs="xs" :sm="sm" :md="md" v-if="showRandomLength">
          <el-form-item-plus
            :label="$t('menu.dev.field.field.item_random_length', '随机数长度')"
            prop="config.item_random_length"
          >
            <el-input
              v-model="modelValue.config.item_random_length"
              :style="commonInputStyle"
              :placeholder="
                $p('menu.dev.field.field.item_random_length', '随机数长度')
              "
            />
          </el-form-item-plus>
        </el-col>

        <!-- 订单格式 -->
        <el-col :xs="xs" :sm="sm" :md="md" v-if="showOrderSn">
          <el-form-item-plus
            :label="$t('menu.dev.field.field.item_sn_format')"
            prop="config.item_sn_format"
          >
            <el-input
              v-model="modelValue.config.item_sn_format"
              :style="commonInputStyle"
              :placeholder="
                $p(
                  'menu.dev.field.field.item_sn_format',
                  '前缀{Y}{M}{D}{H}{I}{S}{R8}{U6}{N2}{P2}',
                )
              "
            />
          </el-form-item-plus>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { computed, onMounted, ref } from 'vue';
import { smartTranslate as $t, transPlaceholder as $p } from '@/lang';
import { useRoute } from 'vue-router';

const xs = 24;
const sm = 12;
const md = 8;

// 当前路由对象
const route = useRoute();
const isApi = computed(() => route.query.app === 'api');

const regularRef = ref(null);
// const regularModel = ref(null);

// Props定义
const props = defineProps({
  modelValue: {
    type: Object,
    required: true,
  },
  commonInputStyle: {
    type: Object,
    default: () => ({ minWidth: '220px' }),
  },
  dictType: {
    type: Array,
    default: () => ['select', 'transfer', 'radio', 'checkbox', 'tree_select'],
  },
  validateTypes: {
    type: Array,
    default: () => ['input', 'textarea', 'password'],
  },
  selectOptions: {
    type: Array,
    default: () => [],
  },
});

const fillCommonSQL = () => {
  if (props.modelValue.config.is_permission === 1) {
    props.modelValue.config.item_options =
      'SELECT pk_field as value, label_field as label, create_id, create_dept FROM table_name WHERE status = 1';
  } else {
    props.modelValue.config.item_options =
      'SELECT pk_field as value, label_field as label FROM table_name WHERE status = 1';
  }
};

const fillTreeSQL = () => {
  if (props.modelValue.config.is_permission === 1) {
    props.modelValue.config.item_options =
      'SELECT pk_field as value, label_field as label, pid_field as pid, create_id, create_dept FROM table_name WHERE status = 1';
  } else {
    props.modelValue.config.item_options =
      'SELECT pk_field as value, label_field as label pid_field as pid,  FROM table_name WHERE status = 1';
  }
};

// 事件定义
const emit = defineEmits([
  'update:modelValue',
  'selectTypeChange',
  'showDictDialog',
  'selectUploadChange',
]);

// 引用
// const dictTypeRef = ref(null);

// 计算属性
const showFormConfig = computed(() => {
  return (
    props.modelValue.config.form_post === 1
    // && route.query.app === 'admin'
  );
});

const noneCreateField = computed(() => {
  return props.modelValue.config.create_field === 'none';
});

const disableSqlAndKeyValue = computed(() => {
  return props.modelValue.config.type === 'switch';
});

const disableKeyValue = computed(() => {
  return ['tree_select'].includes(props.modelValue.config.type);
});

const showSelectType = computed(() => {
  return props.dictType.indexOf(props.modelValue.config.type) !== -1;
});

const showMultipleSelect = computed(() => {
  return ['select', 'list_select', 'tree_select'].includes(
    props.modelValue.config.type,
  );
});

const showSqlOptions = computed(() => {
  return (
    props.dictType.indexOf(props.modelValue.config.type) !== -1 &&
    props.modelValue.config.item_options_type === 'sql'
  );
});

const showSelectRemoteSearch = computed(() => {
  return props.modelValue.config.remote_enabled === 1;
});

const showKvOptions = computed(() => {
  return (
    props.dictType.indexOf(props.modelValue.config.type) !== -1 &&
    props.modelValue.config.item_options_type === 'key_value'
  );
});

const showDictOptions = computed(() => {
  return (
    props.dictType.indexOf(props.modelValue.config.type) !== -1 &&
    props.modelValue.config.item_options_type === 'dict'
  );
});

const showLocationMap = computed(() => {
  return props.modelValue.config.type === 'location_select';
});

const showRichTextEditor = computed(() => {
  return props.modelValue.config.type === 'rich_text_editor';
});

const showSsq = computed(() => {
  return props.modelValue.config.type === 'ssq_select';
});

const showImageUpload = computed(() => {
  return props.modelValue.config.type === 'image_upload';
});

const showFileUpload = computed(() => {
  return props.modelValue.config.type === 'file_upload';
});

const showTextareaRows = computed(() => {
  return props.modelValue.config.type === 'textarea';
});

const showRandomLength = computed(() => {
  return props.modelValue.config.type === 'random';
});

const showOrderSn = computed(() => {
  return props.modelValue.config.type === 'order_sn';
});

const showDateType = computed(() => {
  return ['datetime', 'date_range'].includes(props.modelValue.config.type);
});

const showListSelector = computed(() => {
  return props.modelValue.config.type === 'list_select';
});

const showValidation = computed(() => {
  return props.validateTypes.indexOf(props.modelValue.config.type) !== -1;
});

const showRegularValidation = computed(() => {
  return props.modelValue.config.item_validate === 'regular';
});

const showFunctionValidation = computed(() => {
  return props.modelValue.config.item_validate === 'function';
});

// 日期类型选项
const dateTypeOptions = computed(() => {
  if (props.modelValue.config.type === 'datetime') {
    return [
      { label: 'Date', value: 'date' },
      { label: 'Datetime', value: 'datetime' },
      // { label: 'Dates', value: 'dates' },
      // { label: 'Week', value: 'week' },
      // { label: 'Year', value: 'year' },
      // { label: 'Years', value: 'years' },
      // { label: 'Month', value: 'month' },
      // { label: 'Months', value: 'months' },
    ];
  } else if (props.modelValue.config.type === 'date_range') {
    return [
      { label: 'Date Range', value: 'daterange' },
      { label: 'Datetime Range', value: 'datetimerange' },
      // { label: 'Month Range', value: 'monthrange' },
      // { label: 'Year Range', value: 'yearrange' },
    ];
  }
  return [];
});

function handleSelectRegularChange(e) {
  regularRef.value.options.forEach((item) => {
    if (item.value === e) {
      props.modelValue.config.item_regular_content = item.value;
      props.modelValue.config.item_regular_type = item.label;
    }
  });
}

// 事件处理
const handleSelectTypeChange = (type) => {
  emit('selectTypeChange', type);
};

const handleSelectUploadChange = (type) => {
  emit('selectUploadChange', type);
};

const handleShowDictDialog = () => {
  emit('showDictDialog');
};

// // 监听器
// watch(
//   () => formData.value.config.item_regular_type,
//   (item_regular) => {
//     formData.value.config.item_regular_content = item_regular;
//   },
// );

// 暴露方法
defineExpose({
  // dictTypeRef,
});
</script>

<style lang="scss" scoped>
.form-section {
  margin: 5px;
  border: 1px solid #dcdfe6;
  padding: 5px;
  border-radius: 4px;
}
</style>
